package com.yfunc.ibatis3.orm;

import java.util.HashMap;


public class CommandType {
	
	private static CommandType helper =  new CommandType();
	private HashMap<String, Type> types;
	private HashMap<Class, EntityInfo> entities;
	
	private CommandType(){
		types = new HashMap<String, Type>();
		entities = new HashMap<Class, EntityInfo>();
		for (Type type :  Type.values()) {
			types.put(type.toKey()  , type);
		}
	}
	
	public static boolean isHandlerType(String id) {
		return id != null && id.startsWith(EntityMapper.class.getName().toLowerCase());
	}
	
	public static Type getType(String id) {
		if (helper.types.containsKey(id.toLowerCase())) {
			return helper.types.get(id.toLowerCase());
		}
		return null;
	}
	
	public enum Type{
		INSERT {
			@Override
			public String toSQL(Class entityClass) {
				return getEntityInfo(entityClass).insertSQL();
			}
		},
		UPDATE {
			@Override
			public String toSQL(Class entityClass) {
				return getEntityInfo(entityClass).updateSQL();
			}
		},
		DELETE {
			@Override
			public String toSQL(Class entityClass) {
				return getEntityInfo(entityClass).deleteSQL();
			}
		},
		DELETEBYID {
			@Override
			public String toSQL(Class entityClass) {
				return getEntityInfo(entityClass).deleteSQL();
			}
		},
		FINDBYID {
			@Override
			public String toSQL(Class entityClass) {
				return getEntityInfo(entityClass).fingByIdSQL();
			}
		},
		FINDALL {
			@Override
			public String toSQL(Class entityClass) {
				return getEntityInfo(entityClass).fingAllSQL();
			}
		};

		public String toSQL(Object parameter){
			return toSQL(parameter.getClass());
		}
		
		public String toKey(){
			String key = EntityMapper.class.getName() + "." + this.name();
			return key.toLowerCase();
		}
		
		public boolean isType(String key){
			return key != null && toKey().equals(key.toLowerCase());
		}
		
		public abstract String toSQL(Class entityClass);
		
		protected EntityInfo getEntityInfo(Class entitClass) {
			EntityInfo entityInfo = null;
			if (!helper.entities.containsKey(entitClass)) {
				entityInfo = new EntityInfo(entitClass);
				helper.entities.put(entitClass, entityInfo);
			} else {
				entityInfo = helper.entities.get(entitClass);
			}
			return entityInfo;
		}
	}
}
